<template>
  <div style="padding: 30px;">
    <h2 style="margin-bottom: 20px;">修改密码</h2>
    <el-card>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="form.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password" show-password></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认修改</el-button>
          <el-button @click="router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const formRef = ref(null)

const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) return

    axios.put('/server/member/updatePassword', {
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword
    }, {
      headers: {
        'Authorization': localStorage.getItem('token')
      }
    }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('密码修改成功，请重新登录')
        localStorage.removeItem('token')
        router.push('/MemberLogin')
      } else {
        ElMessage.error(res.data.message || '修改失败')
      }
    }).catch(() => {
      ElMessage.error('请求失败，请稍后重试')
    })
  })
}
</script>

<style scoped>
h2 {
  font-weight: bold;
}
</style>
